<?php
namespace Util;
class Rsa{
	/*
	 * 要加密的数据
	 * @param data：要加密的数据
	 * @return array
	 */
	public static function get_encrypt_data($data){
		$merId = 'DOPCHN000258';//商户号
		$symmetric_key = md5(\Util\Character::randStr(6));//对称密钥
		$ts = time();//时间戳
		//要加密的密文
    	$encKeyStr = $ts.$symmetric_key;
    	$config['pk'] = C('public_key');
		$config['rk'] = C('private_key');
		//公钥加密  
		openssl_public_encrypt($encKeyStr, $encrypted, $config['pk']);
		//密钥密文
		$encKey = strtoupper(bin2hex($encrypted));
		//业务数据密文
		$encData = des_encrypt(substr($symmetric_key,0,8),json_encode($data));
		$ver = '1.0';
		//macStr
		$macStr = $merId.$ver.$ts.$encData;
		$macStr = sha1($macStr);
		openssl_private_encrypt($macStr, $maced, $config['rk']); //私钥加密
		$mac = strtoupper(bin2hex($maced));//bin2hex: ASCII 字符的字符串转换为十六进制值,全部转化成大写
		//返回加密数据
		$data = array(
		  'ver' => $ver,
		  'merId' => $merId,
		  'ts' => $ts,
		  'encKey' => $encKey,
		  'encData' => $encData,
		  'mac' => $mac,
		);
		return $data;
	}

	/*
	 * 要加密的数据
	 * @param data：要加密的数据
	 * @return array
	 */
	public static function get_decrypt_data($ret_data){
		$config['pk'] = C('public_key');
		$config['rk'] = C('private_key');
		if($ret_data['ver'] == '1.0'){
    		$macStr = $ret_data['retCode'].$ret_data['retMsg'].$ret_data['ver'].$ret_data['ts'].$ret_data['encData'];
    		$macStr=bin2hex(hash('sha256',mb_convert_encoding($macStr, 'gbk', 'utf-8'),true));
    		$res = openssl_public_decrypt(hex2bin(strtolower($ret_data['mac'])),$reqMac,$config['pk']);
    		//转换十六进制字符串为二进制字符串
    		if($reqMac == $macStr){
    			//验证mac成功
    			openssl_private_decrypt(hex2bin(strtolower($ret_data['encKey'])),$reqKey,$config['rk']);
    			$symmetric_key = str_replace($ret_data['ts'],'',$reqKey);//对称密钥
    			//解密业务数据密文
    			$json = des_decrypt(substr($symmetric_key,strlen($symmetric_key)-8,8),$ret_data['encData']);
    			$data = json_decode($json,true);
    			return $data;
    		}
    	}
	}
}